<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="收益时间" prop="time">
        <el-date-picker clearable
                        v-model="queryParams.time"
                        type="date"
                        value-format="yyyy-MM"
                        placeholder="请选择收益时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="时间范围" prop="time">
      <el-date-picker
        v-model="queryParams.value1"
        type="monthrange"
        range-separator="To"
        start-placeholder="Start month"
        end-placeholder="End month"
      />
      </el-form-item>
      <el-form-item label="客户ID" prop="customId">
        <el-input
          v-model="queryParams.customId"
          placeholder="请输入客户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:earnings:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:earnings:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:earnings:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:earnings:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="earningsList"   stripe  border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="收益编号" align="center" prop="id" />
      <el-table-column label="客户名称" align="center" prop="customName" />
      <el-table-column label="收益时间" align="center" prop="time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.time, '{y}-{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="节省的电量(kmh)" align="center" prop="conserveElectricity" />
      <el-table-column label="收益金额(元)" align="center" prop="earningsAmount" />
      <el-table-column label="减排碳量(kg)" align="center" prop="carbonEmissions" />
      <el-table-column label="收益详情" align="center"  >
        <template #default="scope" >
          <el-button @click="detail(scope.row)" type="error">详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="公司分润(元)" align="center" prop="firmAmount" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:earnings:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:earnings:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改收益对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="选择客户:" prop="customId">
              <el-select v-model="form.customId"
                         placeholder="请选择客户"
                         filterable
                         clearable>
                <el-option
                  v-for="dict in customIdList"
                  :key="dict.customId"
                  :label="dict.customName"
                  :value="dict.customId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="节省的电量(kwh):" prop="conserveElectricity">
          <el-input-number v-model="form.conserveElectricity" placeholder="请输入电量" type="number" min="0"/>
        </el-form-item>
        </el-col>
          <el-col :span="12">
        <el-form-item label="收益金额(元):" prop="earningsAmount">
          <el-input-number v-model="form.earningsAmount" placeholder="请输入金额" type="number" min="0"/>
        </el-form-item>
        </el-col>
          <el-col :span="12">
        <el-form-item label="收益时间:" prop="time">
          <el-date-picker clearable
                          v-model="form.time"
                          type="month"
                          value-format="yyyy-MM"
                          placeholder="请选择时间">
          </el-date-picker>
        </el-form-item>
          </el-col>
<!--        <el-form-item label="部门配置" prop="departmentAllocation">-->
<!--          <el-input v-model="form.departmentAllocation" placeholder="请输入部门配置" />-->
<!--        </el-form-item>-->
<!--        <el-col :span="12">-->
<!--        <el-form-item label="组长配置(%):" prop="leaderAllocation">-->
<!--          <el-input-number v-model.number="form.leaderAllocation" placeholder="请输入组长配置" type="number" max="100" min="0"-->
<!--                           @change="onInputChange('leaderAllocation')"></el-input-number>-->
<!--        </el-form-item>-->
<!--        </el-col>-->
<!--          <el-col :span="12">-->
<!--        <el-form-item label="组员配置(%):" prop="crewAllocation">-->
<!--          <el-input-number v-model.number="form.crewAllocation" placeholder="请输入组员配置" type="number" max="100" min="0"-->
<!--                           @change="onInputChange('crewAllocation')"></el-input-number>-->
<!--        </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--        <el-form-item label="客户配置(%):" prop="customAllocation">-->
<!--          <el-input-number v-model.number="form.customAllocation" placeholder="请输入客户配置" type="number" max="100" min="0"-->
<!--                           @change="onInputChange('customAllocation')"></el-input-number>-->
<!--        </el-form-item>-->
<!--          </el-col>-->
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="detailTitle" :visible.sync="detailOpen" width="550px" append-to-body>
      <el-table border stripe  :data="detailList">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" />
<!--        <el-table-column label="收益编号" align="center" prop="earningsId" />-->
        <!--      <el-table-column label="用户ID" align="center" prop="userId" />-->
        <el-table-column label="用户名称" align="center" prop="userName" />
        <el-table-column label="收益金额" align="center" prop="earningsAmount" />
        <el-table-column label="收益时间" align="center" prop="time" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.time, '{y}-{m}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancels">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEarnings, getEarnings, delEarnings, addEarnings, updateEarnings } from "@/api/business/earnings";
import {getCustomId} from "@/api/business/custom";
import {listRecords} from "@/api/business/records";

export default {
  name: "Earnings",
  data() {
    return {
      // 遮罩层
      loading: true,
      detailOpen: false,
      detailTitle:"收益详情",
      detailList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 收益表格数据
      earningsList: [],
      customIdList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        conserveElectricity: null,
        earningsAmount: null,
        time: null,
        createdBy: null,
        updatedBy: null,
        createdAt: null,
        updatedAt: null,
        customId: null,
        departmentAllocation: null,
        leaderAllocation: null,
        crewAllocation: null,
        customAllocation: null,
        conservelAmount: null,
        carbonEmissions: null
      },
      // 表单参数
      form: {
        leaderAllocation: 0,
        crewAllocation: 0,
        customAllocation: 0
      },
      maxValue: 100,

      // 表单校验
      rules: {
        customId: [
          { required: true, message: "客户不能为空", trigger: "blur" }
        ],
        conserveElectricity: [
          { required: true, message: "电量不能为空", trigger: "blur" }
        ],
        earningsAmount: [
          { required: true, message: "收益金额不能为空", trigger: "blur" }
        ],
        time: [
          { required: true, message: "收益时间不能为空", trigger: "blur" }
        ],
        leaderAllocation: [
          { required: true, message: "配置不能为空", trigger: "blur" }
        ],
        crewAllocation: [
          { required: true, message: "配置不能为空", trigger: "blur" }
        ],
        customAllocation: [
          { required: true, message: "配置不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getCustomIds()
  },
  methods: {
    cancels(){
      this.detailOpen = false;
    },
    detail(row){
      this.detailList = [];
      const querys = {
        earningsId: row.id,
      }
      listRecords(querys).then(response => {
        this.detailList = response.rows;
        this.detailOpen = true;
      });
    },
    onInputChange(prop) {
      const total = this.form.leaderAllocation + this.form.crewAllocation + this.form.customAllocation;

      console.log("89090",prop,this.form[prop])
      if (total > 100) {
        //alert("配置总和不能超过100%，请调整合适的数值")
         this.form[prop] -= total - 100; // 调整当前输入的值
      }
    },
    /** 查询收益列表 */
    getList() {
      this.loading = true;
      listEarnings(this.queryParams).then(response => {
        this.earningsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getCustomIds(){
      getCustomId().then(response => {
        this.customIdList = response.data;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        conserveElectricity: null,
        earningsAmount: null,
        time: null,
        createdBy: null,
        updatedBy: null,
        createdAt: null,
        updatedAt: null,
        delFlag: null,
        customId: null,
        departmentAllocation: null,
        leaderAllocation: null,
        crewAllocation: null,
        customAllocation: null,
        conservelAmount: null,
        carbonEmissions: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加收益";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getEarnings(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改收益";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateEarnings(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEarnings(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('删除该收益后，对应的用户收益也会被删除，是否确认删除！！！').then(function() {
        return delEarnings(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/earnings/export', {
        ...this.queryParams
      }, `earnings_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

